package com.hex.ds.code.detection.transfer.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.extra.ftp.Ftp;
import com.hex.ds.code.detection.transfer.service.FileTransferService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Package com.hex.ds.code.detection.component.file.transfer.service.impl
 * @ClassName FileTransferServiceImpl
 * @Description 文件传输-业务接口实现
 * @Author Wang zhihao
 * @Date 2023/9/8 17:48
 * @Version v1.0
 **/
@Slf4j
@Service
public class FileTransferServiceImpl implements FileTransferService {

    private double calculateSize(Ftp ftp, String path) {
        double size = 0;
        try {
            List<FTPFile> files = listFiles(ftp, path);
            for (FTPFile file : files) {
                if (!file.isDirectory()) { // 只计算文件的大小
                    size += file.getSize();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("【文件传输】计算目录大小时发生错误: " + e.getMessage(), e);
        }
//        return NumberUtil.round(size / (1024.0 * 1024.0 * 1024.0), 2).doubleValue();
        return NumberUtil.round(size, 2).doubleValue();
    }


    /**
     * @param ftp
     * @Method closeFtp
     * @Param
     * @Return void
     * @Description 公共关闭FTP方法
     * @Author Wang zhihao
     * @Date 2023/9/11 20:04
     * @Version V1.0
     */
    private void closeFtp(Ftp ftp) {
        try {
            ftp.close();
        } catch (Exception e) {
            log.error("【文件传输】FTP关闭失败，请检查异常情况");
        }
    }

    /*
     * @Method: listFiles <br>
     * @Param: [fileTransfer] <br>
     * @Return: java.util.List<java.lang.String> <br>
     * @Description：获取指定目录下所有文件<br>
     * @Author： wz.li<br>
     * @Date： 2023/11/9 17:42 <br>
     * @Version： V2.0.2<br>
     */
    @Override
    public List<FTPFile> listFiles(Ftp ftpClient, String fileDir) throws Exception {
        List<FTPFile> fileList = new ArrayList<>();
        try {
            boolean isDirExist = ftpClient.exist(fileDir);
            if (!isDirExist) {
                log.error("【FTP连接】该目录不存在，请检查");
                return fileList;
            } else {
                fileDir = fileDir.endsWith("/") ? fileDir : fileDir + "/";
                return traverseRemoteDirectory(ftpClient, fileDir);
            }
        } catch (Exception e) {
            throw new Exception("【文件传输】获取指定目录下所有文件异常：" + e.getMessage(), e);
        }
    }

    private void closeFtp(FTPClient ftpClient) {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
     * @Method: traverseRemoteDirectory <br>
     * @Param: [ftpClient, remoteDirPath] <br>
     * @Return: java.util.List<java.lang.String> <br>
     * @Description：递归遍历子目录<br>
     * @Author： wz.li<br>
     * @Date： 2023/11/7 16:46 <br>
     * @Version： V2.0.2<br>
     */
    private List<FTPFile> traverseRemoteDirectory(Ftp ftpClient, String remoteDirPath) {
        List<FTPFile> filePathList = new ArrayList<>();
        FTPFile[] files = ftpClient.lsFiles(remoteDirPath);
        for (FTPFile file : files) {
            if (file.isDirectory()) {
                filePathList.addAll(traverseRemoteDirectory(ftpClient, remoteDirPath + "/" + file.getName()));
            } else {
                filePathList.add(file);
            }
        }
        return filePathList;
    }

}
